package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"github.com/google/uuid"
	"goods_srv/goods"
	"order_srv/order"
	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 创建订单

	//判断商品是否存在
	detail, err := l.svcCtx.GoodsSrv.GoodsDetail(l.ctx, &goods.GoodsDetailRequest{GoodsId: int64(req.GoodsId)})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if detail.GoodsID == 0 {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "商品不存在",
		}, err
	}

	//判断库存是否充足
	stock, _ := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: int64(req.GoodsId)})

	fmt.Println("获取到的库存", stock.GoodsStock)

	if stock.GoodsStock < req.Num {
		return &types.RegMsgResponse{
			Code: -2,
			Msg:  "商品库存不足",
		}, err
	}

	//模拟用户登录 UserID
	userId := l.ctx.Value("userId").(int)

	orderSn := uuid.NewString() //订单编号

	amount := detail.GoodsPrice * float32(req.Num) //商品总价

	//创建订单
	_, err = l.svcCtx.OrderSrv.CreateOrder(l.ctx, &order.CreateOrderRequest{
		UserId:  int64(userId),
		OrderSn: orderSn,
		Amount:  amount,
		Payment: req.Payment,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	price := strconv.FormatFloat(float64(amount), 'f', -1, 32)

	//支付接口
	url := pkg.AlipayPamela(orderSn, price)

	return &types.RegMsgResponse{
		Code: 0,
		Msg:  "订单创建成功",
		Data: map[string]interface{}{
			"alipayUrl": url,
		},
	}, err
}
